import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:rongcloud_im_wrapper_plugin/rongcloud_im_wrapper_plugin.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../../data/stats/bt_log_pages.dart';
import '../../../data/stats/bt_log_pv_manger.dart';
import '../../../data/store/bt_google_translation_store.dart';
import '../../../data/store/bt_hive_logon_store.dart';
import '../../../part/bt_rc_im_engine.dart';
import '../../utils/bt_constants.dart';
import '../../utils/bt_event_bus.dart';
import '../utils/bt_constants.dart';
import 'bt_message.dart';

class BtChatModel extends ChangeNotifier {
  late final String _targetId;

  late final String _targetAvatar;

  String get targetAvatar => _targetAvatar;

  String _userId = '';

  String _userAvatar = '';

  String get userAvatar => _userAvatar;

  bool _holdToTalk = false;

  bool get holdToTalk => _holdToTalk;

  bool _showEmoji = false;

  bool get showEmoji => _showEmoji;

  bool? _voiceRecording;

  bool? get voiceRecording => _voiceRecording;

  bool _isCustomerService = false;

  bool get isCustomerService => _isCustomerService;

  bool _autoTranslation = false;

  bool get autoTranslation => _autoTranslation;

  final List<int> _markedReadVoiceMsgIds = [];

  final ScrollController _scrollController = ScrollController();

  ScrollController get scrollController => _scrollController;

  final List<BtMessage> _messageList = [];

  List<BtMessage> get messageList => _messageList;

  var tfCtl = TextEditingController();

  bool _followed = false;

  bool get followed => _followed;

  BtChatModel(String targetId, String targetAvatar) {
    _targetId = targetId;
    _targetAvatar = targetAvatar;

    loadUserInfo();
    _pullHistoryMessages();
  }

  Future<void> loadUserInfo() async {
    var data = await BtHiveLogonStore().getData();
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    _userId = data?.userId ?? '';
    _userAvatar = data?.avatarUrl ?? '';
    _autoTranslation = prefs.getBool(autoTranslateFlag) ?? false;
    _isCustomerService = _targetId == prefs.getString(userServiceAccountId);
    if (_isCustomerService) {
      BtLogPvManger.stat(page: BtLogPages.customer);
    }

    notifyListeners();
  }

  void setFollowed(bool followed) {
    _followed = followed;
    notifyListeners();
  }

  void setHoldToTalk(bool holdToTalk) {
    _holdToTalk = holdToTalk;
    notifyListeners();
  }

  void setVoiceRecording(bool? voiceRecording) {
    _voiceRecording = voiceRecording;
    notifyListeners();
  }

  void setShowEmoji(bool showEmoji) {
    _showEmoji = showEmoji;
    notifyListeners();
  }

  bool isSenderByMessage(RCIMIWMessage? message) {
    return message?.senderUserId == _userId;
  }

  void addMarkedReadVoiceMsgId(int msgId) {
    _markedReadVoiceMsgIds.add(msgId);

    notifyListeners();
  }

  bool isMessageMarkedRead(int msgId) {
    return _markedReadVoiceMsgIds.contains(msgId);
  }

  void onBackspacePressed() {
    tfCtl
      ..text = tfCtl.text.characters.toString()
      ..selection = TextSelection.fromPosition(TextPosition(offset: tfCtl.text.length));
  }

  void setTranslatedMessageText(BtMessage btMessage, String originText) {
    if (_autoTranslation) {
      BtGoogleTranslationStore().getTranslatedText(originText).then((value) {
        btMessage.translatedText = value;
        notifyListeners();
      });
    } else {
      btMessage.translatedText = BtGoogleTranslationStore().getTranslatedTextFromCache(originText);
    }
  }

  void translateText(BtMessage btMessage) {
    btMessage.translating = true;
    notifyListeners();

    BtGoogleTranslationStore()
        .getTranslatedTextByGoogleTranslate((btMessage.message as RCIMIWTextMessage).text ?? '')
        .then((value) {
      btMessage.translating = false;
      btMessage.translatedText = value;
      notifyListeners();
    }).catchError((error) {
      btMessage.translating = false;
      notifyListeners();
    });
  }

  void _pullHistoryMessages() {
    BtRcImEngine().pullHistoryMessages(_targetId, DateTime.now().millisecondsSinceEpoch,
        callback: IRCIMIWGetMessagesCallback(
          onSuccess: (messageList) async {
            for (RCIMIWMessage item in messageList ?? []) {
              BtMessage btMessage =
                  BtMessage(isSender: isSenderByMessage(item), message: item, status: 1, translating: false);
              _messageList.add(btMessage);
              if (item.messageType == RCIMIWMessageType.text) {
                setTranslatedMessageText(btMessage, (item as RCIMIWTextMessage).text ?? '');
              }
            }
            notifyListeners();

            _registerMessageReceiver();
            await BtRcImEngine().clearUnreadCount(_targetId, DateTime.now().millisecondsSinceEpoch);
            eventBus.fire(BtEventFn(freshConversationList));
          },
          onError: (e) {
            if (kDebugMode) {
              print(e);
            }
          },
        ));
  }

  _registerMessageReceiver() {
    eventBus.on<BtEventFn>().listen((event) {
      if (event.refresh == messageReceived) {
        var message = event.obj as RCIMIWMessage;
        int sentTime = message.sentTime ?? 0;
        int hisSentTime = _messageList[0].message!.sentTime ?? 0;

        if (message.senderUserId == _targetId && sentTime > hisSentTime) {
          BtMessage btMessage = BtMessage(isSender: false, message: message, status: 1, translating: false);
          messageList.insert(0, btMessage);
          if (message.messageType == RCIMIWMessageType.text) {
            setTranslatedMessageText(btMessage, (message as RCIMIWTextMessage).text ?? '');
          }

          notifyListeners();
        }
      }
    });
  }

  Future<void> sendTextMessage() async {
    if (tfCtl.text.trim().isEmpty) {
      return;
    }
    RCIMIWTextMessage? textMessage = await BtRcImEngine().createTextMessage(_targetId, tfCtl.text);
    BtMessage btMessage = BtMessage(isSender: true, message: textMessage, status: 0, translating: false);
    RCIMIWSendMessageCallback? callback =
        RCIMIWSendMessageCallback(onMessageSent: (int? code, RCIMIWMessage? message) {
      btMessage.message = message;
      btMessage.status = code == 0 ? 1 : 2;

      notifyListeners();
      eventBus.fire(BtEventFn(freshConversationList));
    });
    _messageList.insert(0, btMessage);
    notifyListeners();

    tfCtl.clear();
    setShowEmoji(false);
    await BtRcImEngine().sendTextMessage(textMessage, callback: callback);
  }

  Future<void> sendVoiceMessage(path, duration) async {
    RCIMIWVoiceMessage? voiceMessage = await BtRcImEngine().createVoiceMessage(_targetId, path, duration);
    BtMessage btMessage = BtMessage(isSender: true, message: voiceMessage, status: 0, translating: false);
    RCIMIWSendMediaMessageListener? listener = RCIMIWSendMediaMessageListener(
        onMediaMessageSending: (RCIMIWMediaMessage? message, int? progress) {},
        onMediaMessageSent: (int? code, RCIMIWMediaMessage? message) {
          btMessage.message = message;
          btMessage.status = code == 0 ? 1 : 2;

          notifyListeners();
          eventBus.fire(BtEventFn(freshConversationList));
        });
    _messageList.insert(0, btMessage);
    notifyListeners();

    await BtRcImEngine().sendVoiceMessage(voiceMessage, listener);
  }

  Future<void> pickAndSendImageMessage() async {
    if (!await Permission.photos.isGranted) {
      var permissionStatus = await Permission.photos.request();
      if (permissionStatus != PermissionStatus.granted) {
        EasyLoading.showToast("You have not authorised this permission.");
        return;
      }
    }
    var res = await ImagePicker().pickImage(source: ImageSource.gallery);
    if (res != null) {
      RCIMIWImageMessage? imageMessage = await BtRcImEngine().createImageMessage(_targetId, res.path);
      BtMessage btMessage = BtMessage(isSender: true, message: imageMessage, status: 0, translating: false);
      RCIMIWSendMediaMessageListener? listener = RCIMIWSendMediaMessageListener(
          onMediaMessageSending: (RCIMIWMediaMessage? message, int? progress) {},
          onMediaMessageSent: (int? code, RCIMIWMediaMessage? message) {
            btMessage.message = message;
            btMessage.status = code == 0 ? 1 : 2;

            notifyListeners();
            eventBus.fire(BtEventFn(freshConversationList));
          });
      _messageList.insert(0, btMessage);
      notifyListeners();

      await BtRcImEngine().sendImageMessage(imageMessage, listener);
    }
  }

  Future<void> pickAndSendFileMessage() async {
    var result = await FilePicker.platform.pickFiles();
    if (result != null) {
      RCIMIWFileMessage? fileMessage =
          await BtRcImEngine().createFileMessage(_targetId, result.files.single.path ?? '');
      BtMessage btMessage = BtMessage(isSender: true, message: fileMessage, status: 0, translating: false);
      RCIMIWSendMediaMessageListener? listener = RCIMIWSendMediaMessageListener(
          onMediaMessageSending: (RCIMIWMediaMessage? message, int? progress) {},
          onMediaMessageSent: (int? code, RCIMIWMediaMessage? message) {
            btMessage.message = message;
            btMessage.status = code == 0 ? 1 : 2;

            notifyListeners();
            eventBus.fire(BtEventFn(freshConversationList));
          });
      _messageList.insert(0, btMessage);
      notifyListeners();

      await BtRcImEngine().sendFileMessage(fileMessage, listener);
    }
  }

  @override
  void dispose() {
    _scrollController.dispose(); // 在组件销毁时释放ScrollController
    super.dispose();
  }
}
